package thread;

import java.util.PriorityQueue;

/*
 * @author zzr
 * @date: 2025/04/18  14:06
 * @description:
 */
class MyTimerTask2 implements Comparable<MyTimerTask2> {
    private long time;
    private Runnable runnable;
    public MyTimerTask2(Runnable runnable, long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }
    public void run() {
        runnable.run();
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTimerTask2 o) {
        return (int) (this.time - o.time);
    }
}

class MyTimer2 {
    private Thread t = null;
    private PriorityQueue<MyTimerTask2> queue = new PriorityQueue<>();

    Object locker = new Object();

    public void schedule(Runnable runnable, long delay) {
        synchronized (locker) {
            MyTimerTask2 myTimerTask2 = new MyTimerTask2(runnable,delay);
            queue.offer(myTimerTask2);
            // 添加好任务之后就要唤醒线程
            locker.notify();
        }
    }
    public MyTimer2() {
        t = new Thread(() -> {
            while (true) {
                synchronized (locker) {
                    try {
                        while (queue.isEmpty()) {
                            locker.wait();
                        }

                        MyTimerTask2 myTimerTask2 = queue.peek();

                        // 读取当前时间
                        long curTime = System.currentTimeMillis();
                        if (curTime >= myTimerTask2.getTime()) {
                            queue.poll();
                            myTimerTask2.run();
                        } else {
                            // 时间还没到
                            locker.wait(myTimerTask2.getTime() - curTime);
                            if (curTime >= myTimerTask2.getTime()) {
                                queue.poll();
                                myTimerTask2.run();
                            }
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });

        t.start();
    }
}

public class Thread24 {
    public static void main(String[] args) throws InterruptedException {
        MyTimer2 myTimer2 = new MyTimer2();
        myTimer2.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        }, 3000);


        myTimer2.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello new 3000");
            }
        }, 3000);
    }
}
